package com.fangcun;

import javax.servlet.Filter;
import javax.servlet.MultipartConfigElement;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import com.fangcun.common.util.PublicMethod;
import com.fangcun.filter.logs.HttpServletLogFilter;

@SpringBootApplication
@EnableTransactionManagement // 开启事务
@MapperScan("com.fangcun.mapper.**")
@ComponentScan(basePackages = { "com.fangcun" })
public class FangcunApplication {

	public static void main(String[] args) {
		SpringApplication.run(FangcunApplication.class, args);
	}

	// 日志过滤器
	@Bean
	public Filter generalFilter() {
		return new HttpServletLogFilter();
	}

	@Bean
	public CorsFilter corsFilter() {
		final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		final CorsConfiguration config = new CorsConfiguration();
		config.setAllowCredentials(true);
		config.addAllowedOrigin("*");
		config.addAllowedHeader("*");
		config.addAllowedMethod("OPTIONS");
		config.addAllowedMethod("HEAD");
		config.addAllowedMethod("GET");
		config.addAllowedMethod("PUT");
		config.addAllowedMethod("POST");
		config.addAllowedMethod("DELETE");
		config.addAllowedMethod("PATCH");
		source.registerCorsConfiguration("/**", config);
		return new CorsFilter(source);
	}

	// 在启动类里面添加MultipartConfigElement 配置类
	@Bean
	public MultipartConfigElement multipartConfigElement() {
		MultipartConfigFactory factory = new MultipartConfigFactory();
		// 指定临时文件路径，这个路径可以随便写
		factory.setLocation(PublicMethod.getCachePath());
		return factory.createMultipartConfig();
	}

}
